import {ChangeDetectorRef, Component, Inject, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AccountService} from '../_services/account.service';
import {AlertService} from '../_services/alert.service';
import {MatDialog} from '@angular/material/dialog';
import {DialogAddUserComponent} from './dialog.addUser.component';
import {DialogConfirmComponent} from './dialog-confirm.component';
import {User} from '../_models/user';

@Component({templateUrl: 'manage.component.html'})
export class ManageComponent implements OnInit{
  constructor(private route: ActivatedRoute,
              private accountService: AccountService,
              private alertService: AlertService,
              public dialog: MatDialog,
              private changeDetectorRef: ChangeDetectorRef) {
  }
  name: string;
  userList: Array<any>;
  displayedColumns: string[] = ['name', 'gender', 'email', 'phone', 'actions'];
  searchMes: string;
  ngOnInit(): void {
    // this.accountService.user.subscribe(x => this.user = x);
    this.route.queryParams.subscribe(
      params => {
        this.name = params.name;
      }
    );
    this.getTableUpdate();
  }

  private getTableUpdate(): void{
    this.accountService.userList()
      .subscribe({
        next: (resp) => {
          this.userList = resp;
          this.changeDetectorRef.detectChanges();
        },
        error: error => {
          this.alertService.error(error);
        }
      });
  }

  delete(id: string): void {
    const dialogRef = this.dialog.open(DialogConfirmComponent, {
      width: '250px',
      data: {id}
    });
    dialogRef.afterClosed().subscribe(result => {
      this.userList = this.userList.filter(x => x.id !== id);
      // this.getTableUpdate();
      console.log('The dialog was closed');
    });
  }

  add(): void {
    const dialogRef = this.dialog.open(DialogAddUserComponent, {
      width: '500px'
    });

    dialogRef.afterClosed().subscribe(result => {
      this.getTableUpdate();
      console.log('The dialog was closed');
    });
  }

  search(): void {
    if (this.searchMes === '' || this.searchMes === undefined){
      return;
    }
    console.log(this.searchMes);
  }

  edit(user: User): void {
    const dialogRef = this.dialog.open(DialogAddUserComponent, {
      width: '500px',
      data: user
    });

    dialogRef.afterClosed().subscribe(result => {
      this.getTableUpdate();
      console.log('The dialog was closed');
    });
  }
}
